package gdlDao.framework.factory;

import gdlDao.framework.annotation.GdlDao;

import java.util.List;
import java.util.Set;



import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

public class GdlDaoBeanFactory implements BeanFactoryPostProcessor {
	
	private List<String> packagesToScan;
	
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
			throws BeansException {
		try {
			for(String pack : packagesToScan){
				if(org.apache.commons.lang.StringUtils.isNotEmpty(pack)){
				   Set<Class<?>> classSet = PackagesToScanUtil.getClasses(pack);
				   for(Class<?> gdlDaoClass : classSet){
					   if(gdlDaoClass.isAnnotationPresent(GdlDao.class)){
						   ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
						   proxyFactoryBean.setBeanFactory(beanFactory);
						   proxyFactoryBean.setInterfaces(new Class[]{gdlDaoClass});
						   proxyFactoryBean.setInterceptorNames(new String[]{"gdlDaoHandler"});
						   String beanName = getFirstSmall(gdlDaoClass.getSimpleName());
						   if(!beanFactory.containsBean(beanName)){
							   beanFactory.registerSingleton(beanName,proxyFactoryBean.getObject());
						   }
					   }
				   }
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	

	public List<String> getPackagesToScan() {
		return packagesToScan;
	}



	public void setPackagesToScan(List<String> packagesToScan) {
		this.packagesToScan = packagesToScan;
	}



	public static String getFirstSmall(String name){
		name = name.trim();
		if(name.length()>=2){
			return name.substring(0, 1).toLowerCase()+name.substring(1);
		}else{
			return name.toLowerCase();
		}
		
	}
}
